package com.examples.oryarok;
import static com.examples.oryarok.Constants.TAG;
import static com.examples.oryarok.Constants.DATE;
import static com.examples.oryarok.Constants.FROM;
import static com.examples.oryarok.Constants.TABLE_NAME;
import static com.examples.oryarok.Constants.TIME;
import static com.examples.oryarok.HelloTabWidget.dayTemp;
import static com.examples.oryarok.Constants.DATE_DIALOG_ID;
import static android.view.Gravity.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

//http://android.cyrilmottier.com/?p=422 
// This is article about ListView optimization

public class DaylyList extends Activity implements OnClickListener {
	private EditText enterDt;
	private Button butGo;
	private Button butToday;
	//private TextView back;
	//private TextView forward;
	private static MeetDataDbHelper dbEntry;//dbEntry
	//private static StringBuilder dayToday;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_dayly);
        dbEntry = new MeetDataDbHelper(this);
        dayTemp = getCorrentDay();
        //enterDt = (EditText)findViewById(R.id.list_dayly_enterDt);
        //butGo = (Button)findViewById(R.id.button_en);
        //enterDt.setText(dayTemp);
        

//        showDay(dayTemp);
//        showTable(dayTemp); 
    }
	
	
	
	@Override
	public void onResume(){
		super.onResume();
		Log.d(TAG, "Dayly List Resumed");
		setContentView(R.layout.list_dayly);
		butGo = (Button)findViewById(R.id.button_en);
		butGo.setOnClickListener(this);
		butToday = (Button)findViewById(R.id.button_today);
		butToday.setOnClickListener(this);
		View back = findViewById(R.id.dayly_today_back);
		back.setOnClickListener(this);
		View forward = findViewById(R.id.dayly_today_forward);
		forward.setOnClickListener(this);
        showDay(dayTemp);
        showTable(dayTemp); 
	}
	/**
	 * Get current day
	 * @return current day
	 */
	private String getCorrentDay() {
		final Calendar c = Calendar.getInstance();// get the current date
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        String dateNow = sdf.format(c.getTime());
        return dateNow;
	}
	/**
	 * Change current date view to day in parameter
	 * @param day - parameter to show
	 */
	private void showDay(String day){
		TextView today = (TextView) findViewById(R.id.dayly_today);
		today.setText(day);
	}
	/**
	 * Update List Of Meetings by day
	 * @param day - date to update
	 */
	private void showTable(String day) {
		TableLayout table = (TableLayout)findViewById(R.id.tab_dayly);
        TableRow tbRow1;
        TableRow tbRow2;
        TableRow tbRowLine;
        TableRow.LayoutParams tbPar;
        TextView col1;
        TextView col2;
        TextView col3;
        TextView row;
        View line;
        Cursor cursor = getEntry(day);
        boolean hasMoreEntry = cursor.moveToFirst();
                
        try {
        	
        	if (!hasMoreEntry) {
        		tbRow1 = new TableRow(this);
    			row = new TextView(this);
    			row.setPadding(0, 20, 0, 0);
    			row.setText("No meetings today ;)");
    			row.setTextSize(20);
    			row.setGravity(CENTER_HORIZONTAL);
    			tbRow1.addView(row);
    			table.addView(tbRow1);
        	}
        	else {
        		
        		while (hasMoreEntry) {
        			tbRow1 = new TableRow(this);
        			tbRow2 = new TableRow(this);
//        			tbPar = new TableRow.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
//        			tbPar.column = 1;
//        			tbPar.span = 1;
        			tbRowLine = new TableRow(this);
        			col1 = new TextView(this);
        			col2 = new TextView(this);
        			col3 = new TextView(this);
        			row = new TextView(this);
        			line = new View(this);
        			col1.setText(cursor.getString(5));
        			col2.setText(cursor.getString(3));
        			col2.setGravity(RIGHT);
        			col3.setText(" - " + cursor.getString(2));
        			col3.setGravity(RIGHT);
        			row.setText(cursor.getString(1));
        			row.setGravity(RIGHT);
        			//row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        			//row.setLayoutParams(1)
        			//line.setBackgroundColor(color)
        			tbRow1.addView(col1);
        			tbRow1.addView(col2);
        			tbRow1.addView(col3);
        			tbRow2.addView(row);
        			//tbRow2.addView(row, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        			//tbRow2.setLayoutParams(tbPar);
        			table.addView(tbRow1);
        			table.addView(tbRow2);//, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        			hasMoreEntry = cursor.moveToNext();
        		}
        	}
        }
        finally {
        	dbEntry.close();
        }
   
	}

	private Cursor getEntry(String daySt){
		SQLiteDatabase db = dbEntry.getReadableDatabase();
		String select = "(" + DATE + " LIKE '" + daySt + "')";
		Cursor cursor = db.query(TABLE_NAME, FROM, select, null, null, null, TIME + " DESC");
		startManagingCursor(cursor);
		return cursor;
	}



	public void onClick(View v) {
		
			switch (v.getId()) {
	    	case R.id.button_en:
	    		showDialog(DATE_DIALOG_ID);
//	    		enterDt = (EditText)findViewById(R.id.list_dayly_enterDt);
//	    		dayTemp = enterDt.getText().toString();
//	    		Log.d(TAG, "Go button pressed on Dayly List entered day: " + dayTemp);
//	    		onResume();
	    		break;
	    	case R.id.button_today:
	    		dayTemp = getCorrentDay();
	    		Log.d(TAG, "Today button pressed on Dayly List today: " + dayTemp);
	    		onResume();
	    		break;
	    	case R.id.dayly_today_back:
	    		dayTemp = dayMove(dayTemp, false);
	    		Log.d(TAG, "Back pressed on Dayly List today: " + dayTemp);
	    		onResume();
	    		break;
	    	case R.id.dayly_today_forward:
	    		dayTemp = dayMove(dayTemp, true);
	    		Log.d(TAG, "Forward pressed on Dayly List today: " + dayTemp);
	    		onResume();
	    		break;
	    		// More buttons go here (if any) ...
	    	}
	    
		
	}
	
	
	private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    Calendar c = Calendar.getInstance();
                    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
                    c.set(year, monthOfYear, dayOfMonth);
//                	mYear = year;
//                    mMonth = monthOfYear;
//                    mDay = dayOfMonth;
                    dayTemp = sdf.format(c.getTime());
                    onResume();
                }
     };
            
     @Override
     protected Dialog onCreateDialog(int id) {
         switch (id) {
         case DATE_DIALOG_ID:
        	 Calendar c = Calendar.getInstance();
             return new DatePickerDialog(this,
                         mDateSetListener,
                         c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
         }
         return null;
     } 
	
	/**
	 * This function move date by one day with changing larger fields (month, years)
	 * @param dt - date to increment
	 * @param incr - if true increment day else decrement
	 * @return new - date
	 */
	private String dayMove(String dt, boolean incr) {
		Log.d(TAG, "Back pressed on Dayly List today before: " + dt);
		SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
		Calendar c = Calendar.getInstance();
		try {
			c.setTime(sdf.parse(dt));
		} catch (ParseException e) {
			Log.d(TAG, "Error parsing: " + e.toString());
		}
		//c.roll(Calendar.DAY_OF_YEAR, incr);//Increment/decrement one day on Date
		if (incr){
			c.add(Calendar.DATE, 1);//Increment one day on Date
		}
		else {
			c.add(Calendar.DATE, -1);//Decrement one day on Date
		}
			
		dt = sdf.format(c.getTime());  // dt is now the new date
		Log.d(TAG, "Back pressed on Dayly List today after: " + dt);
		return dt;
	}

	
}
